package com.lancoo.znbkxx.teacher.ui.fragment

//import com.lancoo.znbkxx.teacher.model.data.OptionX
//import com.lancoo.znbkxx.teacher.model.data.SubChildX
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.MatcherAdapter
import com.lancoo.znbkxx.teacher.adapter.QuestionAdapter
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtCommentClozeSelectionBinding
import com.lancoo.znbkxx.teacher.model.data.Child
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import java.util.*

/**
 * @author : Admin
 * @date   : 2019/8/6 20:40
 * @desc   :
 */
class ClozeSectionFragment :
        BaseVMFragment<HardSolutionViewModel, FmtCommentClozeSelectionBinding>() {
    lateinit var adapter: QuestionAdapter
    lateinit var matcherAdapter: MatcherAdapter
    private val foot by lazy { layoutInflater.inflate(R.layout.item_choice_footer, null) }
    val data = mutableListOf<Child>()
    private val matcherData = mutableListOf<MultiItemEntity>()
    val type by lazy { requireArguments().getString("title") }
    private val genre by lazy { viewModel.hardSolution.value!!.TkModel.GenreID }
    private val answerType by lazy { viewModel.hardSolution.value!!.TkModel.ChildList[0].ChildAnswerType }

    companion object {
        private const val TITLE = "title"
        fun newInstance(title: String): ClozeSectionFragment {
            val fragment = ClozeSectionFragment()
            val bundle = Bundle()
            bundle.putString(TITLE, title)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun providerContext(): Any? {
        return activity
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_comment_cloze_selection
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        binding.tvQuestionname.text =
                if (viewModel.hardSolution.value!!.TkModel.GenreName.isBlank()) viewModel.hardSolution.value!!.TkModel.TypeName else viewModel.hardSolution.value!!.TkModel.GenreName
        binding.tvQuestionnum.text =
                "(共${viewModel.hardSolution.value!!.TkModel.TotalItemCount}个小题)"
        binding.tvFrom.text=HtmlUtils.setText("来源:<font color='#0099ff'>${viewModel.hardSolution.value!!.TkModel.Resource}</font>")
        initWebview()
        initAnswer()
        initRecyclerView()
    }

    private fun initRecyclerView() {
        binding.rv.layoutManager =
                LinearLayoutManager(requireContext()).apply { orientation = RecyclerView.VERTICAL }
        if (answerType == 32) {
            matcherAdapter = MatcherAdapter(matcherData)
            binding.rv.adapter = matcherAdapter
            matcherAdapter.addFooterView(foot)
        } else {
            adapter = QuestionAdapter(
                    viewModel.hardSolution.value!!.StuAllCount,
                    type,
                    genre,
                    R.layout.item_question,
                    data,
                    lifecycle,
                    null
            )
            binding.rv.adapter = adapter
            adapter.addFooterView(foot)
        }
    }

    private fun initWebview() {
        binding.wv.webChromeClient = WebChromeClient()
        binding.wv.addJavascriptInterface(MyJavaScript(), "APP")
        binding.wv.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                val childListSize = viewModel.hardSolution.value!!.TkModel.ChildList.size
                for (a in 0 until childListSize) {
                    val itemListSize = viewModel.hardSolution.value!!.TkModel.ChildList[a].ItemList.size
                    for (b in 0 until itemListSize) {
                        val itemSortIndex = viewModel.hardSolution.value!!.TkModel.ChildList[a].ItemList[b].ItemSortIndex
                        binding.wv.loadUrl(
                                "javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                                        "','" + "#00000000" + "','" + "0px" + "','" + "1px solid #848484" + "')")
                        binding.wv.loadUrl(
                                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                        + "','" + "<font color=\"#00afff\">"
                                        + "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp" + "</font>')"
                        )
                    }
                }
                if (Build.BRAND.toLowerCase(Locale.ROOT).contains("oppo")) {
                    binding.wv.loadUrl(
                            "javascript:window.APP.resize(document.body.getBoundingClientRect().height)")
                }
            }
        }
        var body = ""
        var choice = ""
        viewModel.hardSolution.value!!.TkModel.ChildList[0].ChildOptionList.forEach {
            choice += "<b>${it.OptionIndex}.${it.Option}</b><br/>"
        }
        when (type) {
            "C", "D", "H", "k", "P", "Q", "X" -> body = viewModel.hardSolution.value!!.TkModel.QuesBody
            "m", "U", "b", "d", "f" -> body =
                    viewModel.hardSolution.value!!.TkModel.ChildList[0].ChildAsk
            "N" -> body =
                    if (genre == 20) viewModel.hardSolution.value!!.TkModel.QuesBody else viewModel.hardSolution.value!!.TkModel.ChildList[0].ChildAsk
            "g" -> body =
                    if (genre == 51 || genre == 50 || genre == 27) viewModel.hardSolution.value!!.TkModel.QuesBody else viewModel.hardSolution.value!!.TkModel.ChildList[0].ChildAsk
        }
        if (body == "") {
            binding.wv.visibility = View.GONE
        } else {
            if (answerType == 32) {
                body += choice
            }
            body = body.replace("______________________".toRegex(), "_")
            WebStyleUtils.showWebViewCssStyle(activity, binding.wv, body, false)
        }
    }

    private fun initAnswer() {
        data.clear()
        val sb = StringBuffer()
        val sbAnlysis = StringBuffer()
        val childxList = viewModel.hardSolution.value!!.TkModel.ChildList
        if (answerType == 32) {
            childxList[0].ItemList.forEachIndexed { index, subChildItemX ->
                subChildItemX.Size = childxList[0].ItemList.size
                val optionList = childxList[0].ItemList[index].ItemOptionList
                val optionListModified = childxList[0].ItemList[index].ItemOptionList.filter {
                    it.StuCount != "0人" && it.OptionIndex != childxList[0].ItemList[index].ItemAnswer
                }.sortedByDescending {
                    it.StuCount.substring(0, it.StuCount.lastIndexOf("人")).toInt()
                }.toMutableList()
                optionListModified.forEachIndexed { index, optionX ->
                    optionX.Index = index
                    optionX.parentIndex = subChildItemX.SortIndex
                    optionX.parentSize = subChildItemX.Size
                    optionX.size = optionListModified.size
                }
                subChildItemX.ItemOptionList = optionListModified
                optionList.forEach {
                    if (it.OptionIndex == subChildItemX.ItemAnswer) {
                        subChildItemX.StuCount = it.StuCount
                        subChildItemX.Rate = it.Rate
                    }
                }
            }
            matcherData.addAll(childxList[0].ItemList)
        } else {
            data.addAll(childxList)
        }
        childxList.forEachIndexed { i, childx ->
            if (childx.ChildAnalysis.isEmpty()) {
                sbAnlysis.append("${i + 1}. ...略\n")
            } else {
                if (type != "k" && childx.ChildAnswerType == 2 || childx.ChildAnswerType == 32) {
                    childx.ItemList.forEach { subChildItemX ->
                        sbAnlysis.append(
                                "${subChildItemX.SortIndex}.${subChildItemX.ItemAnalysis}<br></br>")
                    }
                } else {
                    if (childxList.size == 1) {
                        sbAnlysis.append("${childx.ChildAnalysis}<br></br>")
                    } else {
                        sbAnlysis.append("${i + 1}.${childx.ChildAnalysis}<br></br>")
                    }
                }
            }
            if (type == "m" || type == "N" || type == "U" || type == "b" || type == "Q") {
                val answerList = childx.ChildAnswer.split("\$、")
                answerList.forEachIndexed { j, answer ->
                    val str = answer.replace("$/", "/")
                    if (genre == 23 || genre == 20 || type == "U" || type == "b" || type == "Q") {
                        if (answerList.size <= 1) {
                            sb.append("${i + 1}.$str<br>")
                        } else {
                            sb.append("${j + 1}.$str<br>")
                        }
                    } else {
                        sb.append("${j + 1}.$str  ")
                    }
                }
            } else if (childxList.size == 1) {
                sb.append(
                        childx.ItemList[0].ItemAnswer.replace("$/", "或")
                )
            } else if (type == "g" || type == "X") {
                sb.append(
                        "${i + 1}.${
                        childx.ItemList[0].ItemAnswer.replace(
                                "$/",
                                "或"
                        )
                        }<br>"
                )
            } else if (type == "k") {
                val itemList = childx.ItemList
                if (itemList.size > 1) {
                    val answerList = mutableListOf<String>()
                    itemList.forEach {
                        answerList.add(it.ItemAnswer)
                    }
                    sb.append("${i + 1}.${answerList.joinToString("、")}<br>")
                } else {
                    sb.append(
                            "${i + 1}.${
                            itemList[0].ItemAnswer.replace(
                                    "$/",
                                    "或"
                            )
                            }<br>"
                    )
                }
            } else {
                sb.append(
                        "${i + 1}.${
                        childx.ItemList[0].ItemAnswer.replace(
                                "$/",
                                "或"
                        )
                        }  "
                )
            }
        }
        foot.findViewById<TextView>(R.id.tv_answer).text = HtmlUtils.setText(sb.toString())
        if (sbAnlysis.contains("略")) {
            foot.findViewById<TextView>(R.id.tv_analyze).text = "...略"
        } else {
            foot.findViewById<TextView>(R.id.tv_analyze).text =
                    HtmlUtils.setText(sbAnlysis.toString())
        }
    }

    inner class MyJavaScript {
        @JavascriptInterface
        fun resize(height: Float) {
            activity?.runOnUiThread {
                val layoutParams = LinearLayout.LayoutParams(
                        resources.displayMetrics.widthPixels,
                        ((height + 80) * resources.displayMetrics.density).toInt()
                )
                binding.wv.layoutParams = layoutParams
            }
        }
    }

//    override fun onStart() {
//        super.onStart()
//
//    }
}